package com.itany.shop.filter;

import com.itany.shop.util.ParameterUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 石小俊
 * @date 2023年07月11日 10:21
 * 黑名单过滤器,通过对ip的判断设置黑名单
 * 要求在初始化参数中设置黑名单
 * 黑名单中的ip无法访问任意请求
 * 如果是黑名单用户,返回一个响应:您当前无权访问,请先获取访问权限
 * 且黑名单的人员数量不固定,随时可能发生变化
 * 在功能实现之后后期可以更改黑名单人员,但是代码不允许变动
 * 即:后期黑名单的维护只需要修改初始化参数即可,无需修改具体业务代码
 */
//@WebFilter(urlPatterns = "/*",initParams = {
//        @WebInitParam(name = "blackList",value = "192.168.111.46,192.168.111.99")
//})
public class BlackListFilter implements Filter {

    private FilterConfig config;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        config = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String blackList = config.getInitParameter("blackList");
        String[] ips = blackList.split(",");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取访问者的ip地址
        String ip = request.getRemoteAddr();
        if(!ParameterUtil.isNull(blackList)){
            for(String black : ips){
                if(ip.equals(black)){
                    // 此时表示是黑名单用户,无法访问
//                    response.setContentType("text/html;charset=utf-8");
                    PrintWriter out = response.getWriter();
                    out.println("<h1 style='color:red;'>您当前无权访问,请先获取访问权限</h1>");
                    return;
                }
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
